package com.rocky.study.cyclicbarrier;

import java.util.Random;
import java.util.concurrent.*;

public class CyclicBarrierDemo {

    public static void main(String[] args) {

        String[] nameList = {"打野橘右京","射手孙尚香","中单西施","对抗路老夫子","辅助太乙真人"};

        CyclicBarrier barrier = new CyclicBarrier(5);
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            service.execute(new Player(nameList[i],barrier));
        }
    }

    public static class Player implements Runnable {

        private String name;
        private CyclicBarrier cyclicBarrier;

        public Player(String name, CyclicBarrier cyclicBarrier) {
            this.name = name;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            // 这里模拟 玩家加载及等待的情况
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                System.out.println(name + ": 已经加载到100% 加载完成!");
                cyclicBarrier.await();
                //所有 玩家加载完成之后  会唤醒其他阻塞的线程
                System.out.println(name + ": 全军出击!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
